<template>
  <div class="reportMistakeInfoAction el-card is-always-shadow el-card__body">
    <avue-crud
      ref="crud"
      :option="option"
      :table-loading="listLoading"
      :data="tableData"
      :page.sync="page"
      :search.sync="searchForm"
      @search-change="handleFilter"
      @selection-change="selectionChange"
      @on-load="search"
    >      
    <template slot-scope="scope" slot="lineCodeSearch">
        <el-select
          v-model="searchForm.lineCode"
          placeholder="请选择"
          style="width: 150px"
          @change="changeLine"
          filterable
          clearable
        >
          <el-option
            v-for="(item, index) in lineCodes"
            :key="index"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </template>
      <template slot-scope="scope" slot="stationCodeSearch">
        <el-select
          v-model="searchForm.stationCode"
          placeholder="请选择"
          style="width: 150px"
          clearable
          filterable
          @change="changeStation"
        >
          <el-option
            v-for="(item, index) in stationCodes"
            :key="index"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </template>
        <template slot-scope="scope" slot="tvmCodeSearch">
          <el-select v-model="searchForm.tvmCode" placeholder="请选择" style="width: 150px" filterable>
            <el-option
              v-for="(item,index) in tvmCodes"
              :key="index"
              :label="item.tvmCode"
              :value="item.tvmCode">
            </el-option>
          </el-select>
        </template>
      <template slot="menuRight">
        <el-button type="primary" size="mini" @click="beforSubmitData()">提交</el-button>
        <el-button type="primary" size="mini" @click="exportData" hidden>导出</el-button>
      </template>
      <template slot="searchMenu" slot-scope="{row,size}">
        <el-button :size="size" @click="()=>{setSearchFiledsEmpty(row);setSearchFiledsEmpty(searchForm)}" icon="el-icon-delete">清空</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text" size="small" plain @click.stop="preview(scope.row)">预览</el-button>
      </template>
    </avue-crud>
    <open-dialog
      :DialogVisible.sync="submitVisableDialog"
      title="选择结算周期"
      width="35%"
    >
      <el-form v-loading="isShowLoading" element-loading-text = "正在提交数据，请稍后..." element-loading-spinner = "el-icon-loading">
        <el-form-item label="收入日期">
            <el-date-picker type="date" placeholder="选择开始日期" v-model="settleDateAll.startSettleDate" value-format="yyyy-MM-dd" style="width:150px"></el-date-picker>
         ~
            <el-date-picker type="date" placeholder="选择结束时间" v-model="settleDateAll.endSettleDate" value-format="yyyy-MM-dd" style="width:150px"></el-date-picker>
        </el-form-item>
        <div class="bottom-menu-close">
          <el-button type="primary" size="small" @click="submitData">确认</el-button>
          <el-button type="primary" size="small" @click="submitVisableDialog = false"
            >取消</el-button
          >
        </div>
      </el-form>
    </open-dialog>
    <preview ref="preview"></preview>
  </div>
</template>


<script>
    import {getForm, postForm} from '@/api/gen/gen'
    import ExportJsonExcel from "js-export-excel";
    import preview from './preview.vue';
    import moment from 'moment';
    import {
      getgetStationCodes,
      getLineCodes, getSwPmTvmCodeList, isLongPeriodSettlement, setSearchFiledsEmpty,getAutoSubmitFlag
    } from "../../../../api/subwayRat/commonCheck";
    import {exportDataToExcel} from "../../../../api/subwayRat/exportSelf";
    import {
      getShouJieSuanRepairSubmit, repairSubmitXwTvmData,
      waitSubmitMainOptionList,getTvmNotConfirmDatas,getPeriods
    } from "@/api/subwayRat/shouRuJieSuanBuTiJiao/tvm/repairSubmitMain";
    import { dateFormat } from "@/util/date";
    export default {
      components:{preview
      },
      data() {
            return {
              row : {},
              listLoading: true,
              isRunningFlag: true,//表示是否正在自动提交
              fileTemp:{},
              searchForm:{
              },
              settleDateAll:{
                startSettleDate:'',
                endSettleDate:''
              },
              tableData:[],
              page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 10, // 每页显示多少条,
                isAsc: false// 是否倒序
              },
              autoWidth: true,
              downloadLoading: false,
              isShowLongPeriodSettlementBtn:false,//是否展示长周期结算按钮
              multipleSelectionRows:[],
              multipleSelectionKeys:[],
              attendancePerson:{
                attendancePersonId:'',
                attendancePersonJobNo:'',
                attendancePersonName:'',
              },//值班站长
              option:{},
              lineCodes: [],
              stationCodes: [],
              tvmCodes:[],
              submitVisableDialog: false,
              isShowLoading: false,
              settleTime: [],
              lineOfCodes: [],
              stationOfCodes: []
            }
        },
       async created() {
         this.option=waitSubmitMainOptionList(this);
         //this.search();
	       this.isHaveTvmNotConfirmDatas();
        },
        methods: {
          moment,setSearchFiledsEmpty,
          changeLine(v) {
            //改变线路时
            getgetStationCodes(v).then((res) => {
              this.stationCodes = res;
              this.searchForm.stationCode = "";
            });
          },
          changeStation(v){ //改变车站
            let param={};
            param.lineCode=this.searchForm.lineCode;
            param.stationCode=v;
            getSwPmTvmCodeList(param).then(r=>{
              this.tvmCodes=r.data;
            });
          },
          async exportData(){ // 导出
            this.searchForm.pageNo=1;
            this.searchForm.pageSize=1000000000;
            if(this.multipleSelectionRows.length>0){
              let newData = JSON.parse(JSON.stringify(this.multipleSelectionRows));
              exportDataToExcel(newData,this.option.column,'tvm结算-待提交主页');
            }else {
              let res=await getShouJieSuanRepairSubmit(this.searchForm);
              let data = res.data.data;
              exportDataToExcel(data,this.option.column,'tvm结算-待提交主页');
            }
          },
          async search(){
            Object.assign(this.searchForm,this.page);
            this.searchForm.is_not_settle_status=2; //非等于2的情况
            this.searchForm.approvalStatus=0;
            getShouJieSuanRepairSubmit(this.searchForm).then((res)=>{
              this.tableData=res.data.data;
              this.listLoading = false;
              this.page.total=res.data.total;
            });
          },
          preview(row){
              this.$nextTick(()=>{
                this.$refs.preview.search(row);
              });
          },
          async getPeriods(params){
            await getPeriods(params).then((res)=>{
              if(res!=""){
                let beginTime = res.data.beginTime;
                let endTime = res.data.endTime;
                let now = new Date(beginTime);
                let nows = new Date(endTime);
                this.settleDateAll.startSettleDate = dateFormat(now).substring(0, 10);
                this.settleDateAll.endSettleDate = dateFormat(nows).substring(0, 10);
              }
            });
          },
          beforSubmitData(){
            if(this.multipleSelectionRows.length<=0){
              this.$message.warning("请选择需要提交的数据！");
              return;
            }
            this.settleTime = [];
            let lineOfCode = '';
            let stationOfCode = '';
            let revenueOfTime = '';
            this.lineOfCodes = [];
            this.stationOfCodes = [];
            let diffFlag = true;
            for (const table of this.multipleSelectionRows) {
              lineOfCode = table.lineCode;
              stationOfCode = table.stationCode;
              revenueOfTime = table.revenueTime;
              this.settleTime.push(table.revenueTime);
              this.lineOfCodes.push(table.lineCode);
              this.stationOfCodes.push(table.stationCode);
              let a = this.settleTime[0];
              let l = this.lineOfCodes[0];
              let s = this.stationOfCodes[0];
              for (const iteml of this.lineOfCodes) {
                let ll = iteml;
                for (const items of this.stationOfCodes) {
                  let ss = items;
                  if (l !== ll && s !==ss) {
                    this.$message.warning("请检查选择的数据，只能选择同一线路相同车站的数据进行提交！");
                    diffFlag = false;
                    return false;
                  }
                }
              }
              for (const item of this.settleTime) {
                let b = item;
                if (a !== b) {
                  this.$message.warning("请检查选择的数据，只能选择同一收入日期结算周期相同的数据进行提交！");
                  diffFlag = false;
                  return false;
                }
              }
            }
            if(diffFlag==true){
              let params = {
                lineCode: lineOfCode,
                stationCode: stationOfCode,
                revenueTime: revenueOfTime
              };
              this.getPeriods(params);
              setTimeout(() => {
                this.submitVisableDialog = true;
              }, 500)
            }
          },
          submitData(){ //提交信息
            this.$confirm("是否确认提交？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
                  this.isShowLoading = true;
                  let params={
                    idList:this.multipleSelectionRows,
                    startSettleDate:this.settleDateAll.startSettleDate,
                    endSettleDate:this.settleDateAll.endSettleDate
                  }
                  repairSubmitXwTvmData(params).then(res=>{ //提交
                    if(res.data.code==0){
                      this.$message.success("操作成功");
                      this.search();
                      this.isShowLoading = false;
                      this.submitVisableDialog = false;
                    }else{
                      this.$message.error("操作失败");
                      this.isShowLoading = false;
                      this.submitVisableDialog = false;
                    }
                    this.search();
                  }).catch(error=> {
                      this.search();
                      this.isShowLoading = false;
                      this.submitVisableDialog = false;
                  })
                  
            });
          },
          handleSelectionChange(val,a){
            this.multipleSelectionRows=val;
            this.multipleSelectionKeys=[];
            for(let i=0;i<this.multipleSelectionRows.length;i++){
              this.multipleSelectionKeys.push(this.multipleSelectionRows[i].id);
            }
          },
          selectionChange(list){
            this.multipleSelectionRows=list;
            this.multipleSelectionKeys=[];
            for(let i=0;i<list.length;i++){
              this.multipleSelectionKeys.push(list[i].id);
            }
          },
          handleFilter(params, done) {
            Object.assign(this.searchForm,params);
            this.search()
            done()
          },
	        isHaveTvmNotConfirmDatas(){ //是否含有待确认数据
            let param={};
            param.startSettleDate=this.searchForm.startSettleDate;
            param.endSettleDate=this.searchForm.endSettleDate;
            param.lineCode=this.$store.getters.userInfo.lineCode;
            param.stationCode=this.$store.getters.userInfo.stationCode;
            getTvmNotConfirmDatas(param).then(res=>{
              if(res.data.code==0){
                if(res.data.data.tvmcoins>0){
                  let msg="TVM钱箱清点人2未确认："+res.data.data.tvmcoins+"个";             
                  this.$message.warning(msg);
                }
              }
            })
          },

        },
      async mounted() {
        this.search();
        let lineCode=this.$store.getters.userInfo.lineCode;
        let stationCode=this.$store.getters.userInfo.stationCode;
        isLongPeriodSettlement({lineCode:lineCode,stationCode:stationCode}).then(res=>{
          this.isShowLongPeriodSettlementBtn=res.data.data;
        });
        getLineCodes().then((res) => {
          //获取线路
          this.lineCodes = res;
        });

        //是否正在自动提交
        getAutoSubmitFlag({lineCode:lineCode,stationCode:stationCode}).then(res=>{
          if(res.data.code==0){
              if(res.data.data){
                let msg="系统正在自动提交，请勿进行操作！！！";             
                this.$message.warning(msg);
                this.listLoading = false;
                this.isRunningFlag = false;
            }
          }
        })
      }
    }
</script>
<style lang="scss" scoped>
  .bottom-menu-close {
    margin-top: 18px;
    text-align: center;
  }
</style>
